<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/2
 * Time: 16:51
 */
namespace app\api\common;
use think\Controller;
use think\Db;
use think\Exception;

class Task extends Controller
{
    protected static $err_code = 0;

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 超级买手
     * @api {post} /task.super_buyer 超级买手
     * @apiName Task_super_buyer
     * @apiParam {int} member_id 用户id
     * @apiParam {int} page 页码不要加在data里面
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function super_buyer($param){

        if (!isset($param['member_id']) || empty($param['member_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        //开启事务
        Db::startTrans();
        try{
            //检查已被接的任务有没有超时
            $task_list= Db::table('yf_member_task')->field('id,purchase_id,demand_id,create_time')->where(['status'=>0])->select();
            if (!empty($task_list)){
                $time = time();
                foreach ($task_list as$k=>$v){
                    $num = $time - $v['create_time'];
                    if ($num > 900){
                        Db::table('yf_purchase')->where('id',$v['purchase_id'])->setInc('residual_task'); //剩余任务数加1
                        Db::table('yf_demands')->where('id',$v['demand_id'])->setInc('residual_task'); //剩余任务数加1
                        Db::table('yf_member_task')->where('id',$v['id'])->delete(); //删除我的任务
                    }
                }
            }
            $purchase_ids = Db::table('yf_member_task')->field('purchase_id')->where(['member_id'=>['eq',$param['member_id']]])->group('purchase_id')->select();
            $ids = [];
            if (!empty($purchase_ids)){
                foreach ($purchase_ids as $v){
                    $ids[] = $v['purchase_id'];
                }
            }
            //获取未接过的任务列表
            $purchase_list = Db::table('yf_purchase')->field('id,goods_name,img_url,tb_id,price,residual_task')->where(['id'=>['not in',$ids],'residual_task'=>['neq',0]])->order('id desc')->paginate('10');
            $purchase_list = $purchase_list->toArray();
            //事物提交
            Db::commit();
            return ['data'=>$purchase_list,'code' => 200, 'msg' => 'SUCCESS'];
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 我的任务
     * @api {post} /task.my_task 我的任务
     * @apiName Task_my_task
     * @apiParam {int} member_id 用户id
     * @apiParam {int} page 页码不要加在data里面
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function my_task($param){

        if (!isset($param['member_id']) || empty($param['member_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $task_info = Db::table('yf_member_task')->alias('a')->field('a.id,a.spec_name,a.money,a.create_time,a.order_img,b.goods_name,b.img_url')->join('yf_purchase b','a.purchase_id=b.id','LEFT')->where(['a.member_id'=>['eq',$param['member_id']]])->order('a.id desc')->paginate('10');
            if (empty($task_info)){
                self::$err_code = 400024;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $task_info = $task_info->toArray();
            return ['data'=>$task_info,'code' => 200, 'msg' => 'SUCCESS'];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 采购详情
     * @api {post} /task.task_detail 采购详情
     * @apiName Task_task_detail
     * @apiParam {int} member_id 用户id
     * @apiParam {int} purchase_id 采购需求id
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function task_detail($param){

        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['purchase_id']) || empty($param['purchase_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $num = Db::table('yf_member_task')->where(['purchase_id'=>$param['purchase_id'],'member_id'=>$param['member_id']])->count();
            if ($num >0){
                self::$err_code = 400025;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $purchase_info = Db::table('yf_purchase')->alias('a')->field('a.id,a.goods_name,a.tb_id,a.price,a.img_url,a.couponurl,b.receiving_address,b.shop_keeper,b.phone')->join('yf_shop b','a.shop=b.id','left')->where(['a.id'=>$param['purchase_id']])->find();
            if (empty($purchase_info)){
                self::$err_code = 400024;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $demands_list = Db::table('yf_demands')->alias('a')->field('a.id,a.spec_name,a.residual_task,a.price,b.tb_id')->join('yf_purchase b','a.purchase_id=b.id','left')->where(['a.purchase_id'=>$purchase_info['id']])->select();
            $data['info'] = $purchase_info;
            $data['list'] = $demands_list;
            return ['data'=>$data,'code' => 200, 'msg' => 'SUCCESS'];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 接任务
     * @api {post} /task.accept_task 接任务
     * @apiName Task_accept_task
     * @apiParam {int} member_id 用户id
     * @apiParam {int} demand_id 规格需求id
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {int} data.id 我的任务id
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success'
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function accept_task($param){

        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['demand_id']) || empty($param['demand_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        //启动事物
        Db::startTrans();
        try{
            $demand = Db::table('yf_demands')->alias('a')->field('a.*,b.goods_name,b.tb_id,b.is_tmall,b.residual_task all_residual,b.waiting_storage all_waiting')->join('yf_purchase b','a.purchase_id=b.id','LEFT')->where(['a.id'=>$param['demand_id']])->find();
            if ($demand['residual_task'] == 0){
                self::$err_code = 400026;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $data['purchase_id'] = $demand['purchase_id'];
            $data['spec_name'] = $demand['spec_name'];
            $data['money'] = $demand['price'];
            $data['number'] = 1;
            $data['status'] = 0;
            $data['create_time'] = time();
            $data['tb_skuid'] = $demand['tb_skuid'];
            $data['tb_id'] = $demand['tb_id'];
            $data['member_id'] = $param['member_id'];
            $data['demand_id'] = $demand['id'];
            $id = Db::table('yf_member_task')->insertGetId($data);
            if ($id){
                Db::table('yf_demands')->where('id', $demand['id'])->update(['residual_task'=>$demand['residual_task']-1,'waiting_storage'=>$demand['waiting_storage']+1]);
                Db::table('yf_purchase')->where('id', $demand['purchase_id'])->update(['residual_task'=>$demand['all_residual']-1]);
                //事物提交
                Db::commit();
                return ['code'=>200,'data'=>['id'=>$id],'msg'=>'success'];
            }
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 任务详情
     * @api {post} /task.task_info 任务详情
     * @apiName Task_task_info
     * @apiParam {int} member_id 用户id
     * @apiParam {int} task_id 采购需求id
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {int} data.id 是否存在维修店这个角色
     * @apiSuccess {int} data.purchase_id 采购需求id
     * @apiSuccess {String} data.spec_name 规格名称
     * @apiSuccess {String} data.money 货品金额
     * @apiSuccess {String} data.number 采购数量
     * @apiSuccess {String} data.tborder_sn 淘宝订单号
     * @apiSuccess {String} data.courier_sn 物流号
     * @apiSuccess {String} data.wuliu_com 物流公司
     * @apiSuccess {String} data.status 任务状态 0采购中 1等待物流单号 2等待入库 3已入库 4超时任务释放 5任务取消
     * @apiSuccess {String} data.create_time 任务创建时间
     * @apiSuccess {String} data.tb_skuid 淘宝skuid
     * @apiSuccess {String} data.tb_id 淘宝商品id
     * @apiSuccess {String} data.member_id 用户id
     * @apiSuccess {String} data.order_img 订单图片
     * @apiSuccess {String} data.demand_id 需求id
     * @apiSuccess {String} data.goods_name 商品名称
     * @apiSuccess {String} data.couponurl 优惠券地址
     * @apiSuccess {String} data.is_tmall 是否是天猫商品 0是 1不是
     * @apiSuccess {Object} data.trace 物流信息 (无物流单号时为空)
     * @apiSuccess {Bool} data.trace.success 成功与否
     * @apiSuccess {String} data.trace.state 物流状态：2-在途中,3-签收,4-问题件
     * @apiSuccess {Object} data.trace.list 物流信息列表
     * @apiSuccess {String} data.trace.list.AcceptTime 时间
     * @apiSuccess {String} data.trace.list.AcceptStation 描述
     * @apiSuccess {String} data.trace.list.Remark 备注
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success'
     *     data:{
     *           ...
     *	   }
     *
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function task_info($param){

        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['task_id']) || empty($param['task_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $task_info = Db::table('yf_member_task')->alias('a')->field('a.*,b.goods_name,b.is_tmall,b.img_url,c.shop_name,c.receiving_address,c.shop_keeper,c.phone,b.couponurl')->join('yf_purchase b','a.purchase_id=b.id','LEFT')->join('yf_shop c','b.shop=c.id','LEFT')->where(['a.id'=>$param['task_id']])->find();
            if (empty($task_info)){
                self::$err_code = 400027;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            if ($task_info['status'] == 0){
                $task_info['residual_time'] = 900-(time()-$task_info['create_time']);
            }else{
                $task_info['residual_time'] = 0;
            }
            if (!empty($task_info['courier_sn']) && !empty($task_info['wuliu_com'])){
                $requestData= "{'OrderCode':'','ShipperCode':'".$task_info['wuliu_com']."','LogisticCode':'".$task_info['courier_sn']."'}";
                $datas = array(
                    'EBusinessID' => config('wuliu.appid'),
                    'RequestType' => '1002',
                    'RequestData' => urlencode($requestData) ,
                    'DataType' => '2',
                );
                $datas['DataSign'] = urlencode(base64_encode(md5($requestData.config('wuliu.key'))));
                $result=curl_request(config('wuliu.req_url'), $datas);
                if ($result['Success'] == true){
                    $task_info['traces']['state'] = $result['State'];
                    $task_info['traces']['list'] = $result['Traces'];
                    $task_info['traces']['success'] = $result['Success'];
                }else{
                    $task_info['traces']['success'] = $result['Success'];
                    $task_info['traces']['state'] = '';
                    $task_info['traces']['list'] = [];
                }
            }else{
                $task_info['traces']['success'] = false;
                $task_info['traces']['state'] = '';
                $task_info['traces']['list'] = [];
            }
            return ['data'=>$task_info,'code'=>200,'msg'=>'success'];
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 任务提交
     * @api {post} /task.update_task_first 任务提交
     * @apiName Task_update_task_first
     * @apiParam {int} member_id 用户id
     * @apiParam {int} task_id 采购需求id
     * @apiParam {String} tborder_sn 淘宝订单号
     * @apiParam {String} order_img 淘宝订单截图
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明

     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success'
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function update_task_first($param){

        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['task_id']) || empty($param['task_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        if (!isset($param['tborder_sn']) || empty($param['tborder_sn']))
        {
            return ['code' => 400001, 'msg' => '淘宝订单号不能为空'];
        }
        if (!isset($param['order_img']) || empty($param['order_img']))
        {
            return ['code' => 400001, 'msg' => '订单图片不能为空'];
        }
        //启动事物
        Db::startTrans();
        try{
            $tborder_sn = htmlspecialchars($param['tborder_sn']);
            if (Db::table('yf_member_task')->where(['id'=>$param['task_id'],'member_id'=>$param['member_id']])->update(['tborder_sn'=>$tborder_sn,'order_img'=>$param['order_img'],'status'=>1])){
                Db::commit();
                return ['code'=>200,'msg'=>'SUCCESS'];
            }else{
                self::$err_code = 400029;
                throw new Exception(config('error_code.'.self::$err_code));
            }
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Task
     * @apiVersion 1.0.1
     * @apiDescription 添加物流
     * @api {post} /task.update_task_two 添加物流
     * @apiName Task_update_task_two
     * @apiParam {int} member_id 用户id
     * @apiParam {int} task_id 任务id
     * @apiParam {String} courier_sn 物留单号
     * @apiParam {String} wuliu_com 物流公司代码
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明

     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success'
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function update_task_two($param){

        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['task_id']) || empty($param['task_id']))
        {
            return ['code' => 400001, 'msg' => '参数错误'];
        }
        if (!isset($param['courier_sn']) || empty($param['courier_sn']))
        {
            return ['code' => 400001, 'msg' => '物流单号不能为空'];
        }
        if (!isset($param['wuliu_com']) || empty($param['wuliu_com']))
        {
            return ['code' => 400001, 'msg' => '物流公司代码'];
        }

        //启动事物
        Db::startTrans();
        try{
            $courier_sn = htmlspecialchars($param['courier_sn']);
            if (Db::table('yf_member_task')->where(['id'=>$param['task_id'],'member_id'=>$param['member_id']])->update(['courier_sn'=>$courier_sn,'wuliu_com'=>$param['wuliu_com'],'status'=>2])){
                Db::commit();//事物提交
                return ['code'=>200,'msg'=>'SUCCESS'];
            }else{
                self::$err_code = 400029;
                throw new Exception(config('error_code.'.self::$err_code));
            }
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }
}